"use client";

import React, { useState, ChangeEvent, FormEvent } from 'react';
import './register.css';

// 定义表单数据类型
interface FormData {
  username: string;
  email: string;
  password: string;
  confirmPassword: string;
}

// 定义表单错误类型
interface FormErrors {
  username?: string;
  email?: string;
  password?: string;
  confirmPassword?: string;
  form?: string;
}

const RegisterPage: React.FC = () => {
  // 状态管理
  const [formData, setFormData] = useState<FormData>({
    username: '',
    email: '',
    password: '',
    confirmPassword: ''
  });
  
  const [loading, setLoading] = useState<boolean>(false);
  const [errors, setErrors] = useState<FormErrors>({});

  // 处理输入变化
  const handleChange = (e: ChangeEvent<HTMLInputElement>): void => {
    const { name, value } = e.target;
    setFormData((prevState: FormData) => ({
      ...prevState,
      [name]: value
    }));
    
    // 清除相应字段的错误
    if (errors[name as keyof FormErrors]) {
      setErrors((prev: FormErrors) => ({
        ...prev,
        [name]: undefined
      }));
    }
  };

  // 表单验证
  const validateForm = (): boolean => {
    const newErrors: FormErrors = {};
    
    if (!formData.username) {
      newErrors.username = '请输入账号';
    } else if (formData.username.length < 3) {
      newErrors.username = '账号至少需要3个字符';
    }
    
    if (!formData.email) {
      newErrors.email = '请输入电子邮件';
    } else if (!/\S+@\S+\.\S+/.test(formData.email)) {
      newErrors.email = '请输入有效的电子邮件地址';
    }
    
    if (!formData.password) {
      newErrors.password = '请输入密码';
    } else if (formData.password.length < 6) {
      newErrors.password = '密码至少需要6个字符';
    }
    
    if (!formData.confirmPassword) {
      newErrors.confirmPassword = '请确认密码';
    } else if (formData.password !== formData.confirmPassword) {
      newErrors.confirmPassword = '两次输入的密码不一致';
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 处理表单提交
  const handleSubmit = async (e: FormEvent<HTMLFormElement>): Promise<void> => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }
    
    setLoading(true);
    
    try {
      // 这里添加注册逻辑，例如API请求
      console.log('注册信息:', formData);
      
      // 模拟API请求
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 注册成功后的逻辑，例如导航到登录页面或显示成功消息
      alert('注册成功!');
      
    } catch (error) {
      console.error('注册失败:', error);
      setErrors({ form: '注册失败，请稍后重试' });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="auth-container">
      <div className="auth-box">
        <div className="auth-header">
          <h1>创建账户</h1>
          <p>请填写以下信息完成注册</p>
        </div>
        
        {errors.form && (
          <div className="error-banner">
            {errors.form}
          </div>
        )}
        
        <form onSubmit={handleSubmit} className="auth-form">
          <div className="form-group">
            <label htmlFor="username">账号</label>
            <input
              type="text"
              id="username"
              name="username"
              placeholder="请输入您的账号"
              value={formData.username}
              onChange={handleChange}
              className={`input ${errors.username ? 'error' : ''}`}
              disabled={loading}
            />
            {errors.username && <div className="error-message">{errors.username}</div>}
          </div>
          
          <div className="form-group">
            <label htmlFor="email">电子邮件</label>
            <input
              type="email"
              id="email"
              name="email"
              placeholder="请输入您的电子邮件"
              value={formData.email}
              onChange={handleChange}
              className={`input ${errors.email ? 'error' : ''}`}
              disabled={loading}
            />
            {errors.email && <div className="error-message">{errors.email}</div>}
          </div>
          
          <div className="form-group">
            <label htmlFor="password">密码</label>
            <input
              type="password"
              id="password"
              name="password"
              placeholder="请输入您的密码"
              value={formData.password}
              onChange={handleChange}
              className={`input ${errors.password ? 'error' : ''}`}
              disabled={loading}
            />
            {errors.password && <div className="error-message">{errors.password}</div>}
          </div>
          
          <div className="form-group">
            <label htmlFor="confirmPassword">确认密码</label>
            <input
              type="password"
              id="confirmPassword"
              name="confirmPassword"
              placeholder="请再次输入密码"
              value={formData.confirmPassword}
              onChange={handleChange}
              className={`input ${errors.confirmPassword ? 'error' : ''}`}
              disabled={loading}
            />
            {errors.confirmPassword && <div className="error-message">{errors.confirmPassword}</div>}
          </div>
          
          <button type="submit" className={`btn ${loading ? 'loading' : ''}`} disabled={loading}>
            {loading ? '注册中...' : '注册'}
          </button>
        </form>
        
        <div className="auth-footer">
          <p>已有账户? <a href="/user/login">登录</a></p>
        </div>
      </div>
    </div>
  );
};

export default RegisterPage;